package com.adv.ems.service.impl;

import com.adv.ems.manager.impl.BaseManagerImpl;
import com.adv.ems.service.CacheService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.SmartInitializingSingleton;
import org.springframework.stereotype.Service;
import java.time.Duration;
import java.util.List;

@Slf4j
@Service
public class CacheServiceImpl implements CacheService, SmartInitializingSingleton {
    private final List<BaseManagerImpl<?, ?>> managers;

    public CacheServiceImpl(List<BaseManagerImpl<?, ?>> managers) {
        this.managers = managers;
    }

    @Override
    public void refreshCache() {
        log.info("Refresh cache start");
        managers.forEach(BaseManagerImpl::refreshCache);
        log.info("Refresh cache end");
    }

    @Override
    public void afterSingletonsInstantiated() {
        new Thread(() -> {
            while (!Thread.interrupted()) {
                refreshCache();
                try {
                    Thread.sleep(Duration.ofMinutes(15).toMillis());
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
            }
        }).start();
    }
}
